package com.vviton.zyhj.common.utils.idgen;

import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 多机有序的序号生成器
 */
public class ClusterIdMake implements IdMake {

    private static final Log LOG = LogFactory.getLog(ClusterIdMake.class);
    private Random random = new Random();
    private long datacenterId;
    private long workerId;
    private long sequence = 0L;
    // 开始时间，从2016开始
    private long twepoch = 1451577600000L;

    // 数据中心标识位数
    private long datacenterIdBits = 5L;
    // 机器标识位数
    private long workerIdBits = 5L;
    // 机器ID最大值
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 数据中心ID最大值
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    // 毫秒内自增位
    private long sequenceBits = 12L;
    // 毫秒内最大值
    private long sequenceMask = -1L ^ (-1L << sequenceBits);
    // 机器ID偏左移12位
    private long workerIdShift = sequenceBits;
    // 数据中心ID左移17位
    private long datacenterIdShift = sequenceBits + workerIdBits;
    // 时间毫秒左移22位
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    private long lastTimestamp = -1L;

    public ClusterIdMake(long datacenterId, long workerId) {
        // 校验最大值
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.datacenterId = datacenterId;
        this.workerId = workerId;
        LOG.info(String.format("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d", timestampLeftShift, datacenterIdBits, workerIdBits,
                sequenceBits, workerId));
    }

    // 保证有序
    public synchronized long nextId() {

        long timestamp = timeGen();
        // 时间校验
        if (timestamp < lastTimestamp) {
            LOG.error(String.format("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp));
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 随机0-9
            sequence = random.nextInt(10);//0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
    }

    // 等待下一个毫秒的到来 
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    // 当前时间
    protected long timeGen() {
        return System.currentTimeMillis();
    }
}
